package client;

import java.awt.EventQueue;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import server.Marketplace;
import server.Server;

public class Client {
	private View view;
	private Trader trader;
	private Marketplace marketPlace;
	//public static String marketName = "Marketplace";


	
	public Client(View view) throws RemoteException, MalformedURLException, ClassNotFoundException, NotBoundException, SQLException{
		this.view = view;
		//marketPlace = new MarketplaceImpl();
    	//Naming.rebind(marketName, marketPlace);
		marketPlace = (Marketplace)Naming.lookup(Server.marketName);
	}
	
	public void registerNewTrader(String traderName, String traderPassword) throws RemoteException, MalformedURLException, NotBoundException, SQLException {
		TraderImpl trader;
		trader = new TraderImpl(traderName, traderPassword, marketPlace);
		marketPlace.registerTrader(trader);
		this.trader = trader;
		view.setTrader(trader);
	}
	
	public boolean login(String traderName, String traderPassword) throws RemoteException, MalformedURLException, NotBoundException, SQLException{

		boolean success = marketPlace.login(traderName, traderPassword);
		
		if (success)
		{
			TraderImpl trader;
			trader = new TraderImpl(traderName, traderPassword, marketPlace);
			this.trader = trader;
			view.setTrader(trader);
			marketPlace.replaceTrader(trader);
		} else
		{	
			java.awt.EventQueue.invokeLater(new Runnable() {

				@Override
				public void run() {
					JOptionPane.showMessageDialog(null, "Invalid login details");
				}
			});
		}
		return success;	
		

	}
	
	public void logout() throws RemoteException, SQLException{
		if (trader != null){
			marketPlace.logout(trader.getTraderName());
			trader = null;
		}
	}
	
	public void removeTrader(){
		trader = null;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					View view = new View();
					view.setVisible(true);
					Client client = new Client(view);
					view.setClient(client);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
}
